# Scatter - ggplot2
library(ggplot2)

# 1. Basic point plot ----
# Basic scatter----
ggplot(diamonds, aes(carat, price)) + geom_point()

ggplot(diamonds, aes(carat, price)) + geom_point(aes(shape = cut))

ggplot(diamonds, aes(carat, price)) + geom_point(aes(colour = cut))

ggplot(diamonds, aes(carat, price)) + geom_point(aes(colour = cut, size = table))

ggplot(diamonds, aes(carat, price)) + geom_point(alpha = 1/10)

ggplot(diamonds, aes(carat, price)) + geom_point(shape = '.')

# Decorating
p <- ggplot(diamonds, aes(carat, price)) + geom_point(aes(colour = cut))

p + ggtitle("Scatter Plot") +
  theme_economist(base_size = 14) +
  scale_colour_economist() +
  guides(size = guide_legend(title = NULL), colour = guide_legend(title = NULL))

p1 <- ggplot(diamonds, aes(carat, price)) + 
  geom_point(aes(colour = cut, size = table)) +
  ggtitle('Scatter Plot')

p2 <- p1 + theme_wsj(base_size = 12) + scale_colour_wsj() +
  guides(size = guide_legend(title = NULL), colour = guide_legend(title = NULL))
p2

p2 + xlim(1, 2) + ylim(5000, 10000)


# 2. ggplot::geom_point() ----
mtcars$cyl <- as.factor(mtcars$cyl)

ggplot(mtcars, aes(wt, mpg)) +
    geom_point(size = 2, shape = 23)

ggplot(mtcars, aes(wt, mpg)) +
    geom_point(aes(size = qsec))

# labels ----
ggplot(mtcars, aes(wt, mpg)) +
    geom_point() +
    geom_text(label = rownames(mtcars))

# regression line ----
#   geom_smooth(), stat_smooth(), geom_abline()

# geom_smooth(method, se = T, fullrange = F, level = 0.95)
#   method = "loess", default
#   method = "lm", linear model
#   se, display confident interval
#   fullrange, fit spans the full range of the plot
#   level, 95% CI (default)

ggplot(mtcars, aes(wt, mpg)) +
    geom_point() +
    geom_smooth(method = lm)

ggplot(mtcars, aes(wt, mpg)) +
    geom_point() +
    geom_smooth(method = lm, se = FALSE)  # without CI

ggplot(mtcars, aes(wt, mpg)) +
    geom_point() +
    geom_smooth()

# colors and shapes ----

ggplot(mtcars, aes(wt, mpg)) +
    geom_point(shape = 18, color = "steelblue") +
    geom_smooth(method = lm, se = F, 
                linetype = "dashed", color = "darkred")

ggplot(mtcars, aes(wt, mpg)) +
    geom_point(shape = 18, color = "steelblue") +
    geom_smooth(method = lm, linetype = "dashed", 
                color = "darkred", fill = "blue")

# Scatter by groups ----
ggplot(mtcars, aes(wt, mpg, shape = cyl, color = cyl, size = cyl)) +
    geom_point()

# Parted regression line (not for full data)
ggplot(mtcars, aes(wt, mpg, shape = cyl, color = cyl)) +
    geom_point() +
    geom_smooth(method = lm, aes(fill = cyl))

# Regression line for each team
ggplot(mtcars, aes(wt, mpg, shape = cyl, color = cyl)) +
    geom_point() +
    geom_smooth(method = lm, se = F, fullrange = T)

# Manual color/shape/size ----

# Change point shapes and colors manually
ggplot(mtcars, aes(x = wt, y = mpg,
    color = cyl, shape = cyl)) +
    geom_point() +
    geom_smooth(method = lm, se = FALSE, fullrange = TRUE) +
    scale_shape_manual(values = c(3, 16, 17)) +
    scale_color_manual(values = c('#999999', '#E69F00', '#56B4E9')) +
    theme(legend.position = "top")

# Change the point sizes manually
ggplot(mtcars, aes(x = wt, y = mpg, color = cyl, shape = cyl)) +
    geom_point(aes(size = cyl)) +
    geom_smooth(method = lm, se = FALSE, fullrange = TRUE) +
    scale_shape_manual(values = c(3, 16, 17)) +
    scale_color_manual(values = c('#999999', '#E69F00', '#56B4E9')) +
    scale_size_manual(values = c(2, 3, 4)) +
    theme(legend.position = "top")


p <- ggplot(mtcars, aes(x = wt, y = mpg, color = cyl, shape = cyl)) +
    geom_point() + 
    geom_smooth(method = lm, se = FALSE, fullrange = TRUE) +
    theme_classic()
# Use brewer color palettes
p + scale_color_brewer(palette = "Dark2")
# Use grey scale
p + scale_color_grey()

# marginal rugs ----
# geom_rug(sides = "bl")

ggplot(mtcars, aes(wt, mpg, color = cyl)) +
    geom_point() + geom_rug()

ggplot(faithful, aes(eruptions, waiting)) +
    geom_point() + geom_rug()

# scatter with 2d density ----
sp <- ggplot(faithful, aes(eruptions, waiting)) +
    geom_point()
sp + geom_density_2d()
# gradient color
sp + stat_density_2d(aes(fill = ..level..), geom = "polygon")

# change the gradient color
sp + stat_density_2d(aes(fill = ..level..), geom = "polygon") +
    scale_fill_gradient(low = "blue", high = "red")

# scatter with ellipses ----
# one ellipse around all points
ggplot(faithful, aes(waiting, eruptions)) +
    geom_point() +
    stat_ellipse()

# ellipse by groups
p <- ggplot(faithful, aes(waiting, eruptions, color = eruptions > 3)) +
    geom_point()
# change the type of ellipse, "t", "norm","euclid"
p + stat_ellipse(type = "norm")


# scatter with rectangular bins ----
# geom_bin2d() for adding a heatmap of 2d bin counts
# stat_bin_2d() for counting the number of observation in rectangular bins
# stat_summary_2d() to apply function for 2D rectangular bins
p <- ggplot(diamonds, aes(carat, price))
p + geom_bin2d()

# Change the number of bins
p + geom_bin2d(bins = 10)

# Or specify the width of bins
p + geom_bin2d(binwidth = c(1, 1000))

# scatter with marginal density distribution ----
set.seed(1234)
x <- c(rnorm(500, mean = -1), rnorm(500, mean = 1.5))
y <- c(rnorm(500, mean = 1), rnorm(500, mean = 1.7))
group <- as.factor(rep(c(1,2), each = 500))
df <- data.frame(x, y, group)
head(df)

# scatter plot of x and y variables
# color by groups
scatterPlot <- ggplot(df,aes(x, y, color = group)) + 
    geom_point() + 
    scale_color_manual(values = c('#999999','#E69F00')) + 
    theme(legend.position = c(0,1), legend.justification = c(0,1))
scatterPlot

# Marginal density plot of x (top panel)
xdensity <- ggplot(df, aes(x, fill = group)) + 
    geom_density(alpha = .5) + 
    scale_fill_manual(values = c('#999999','#E69F00')) + 
    theme(legend.position = "none")
xdensity

# Marginal density plot of y (right panel)
ydensity <- ggplot(df, aes(y, fill = group)) + 
    geom_density(alpha = .5) + 
    scale_fill_manual(values = c('#999999','#E69F00')) + 
    theme(legend.position = "none")
ydensity

blankPlot <- ggplot() + geom_blank(aes(1,1))+
    theme(plot.background = element_blank(), 
          panel.grid.major = element_blank(),
          panel.grid.minor = element_blank(), 
          panel.border = element_blank(),
          panel.background = element_blank(),
          axis.title.x = element_blank(),
          axis.title.y = element_blank(),
          axis.text.x = element_blank(), 
          axis.text.y = element_blank(),
          axis.ticks = element_blank())

library(gridExtra)
grid.arrange(xdensity, blankPlot, scatterPlot, ydensity,
    ncol = 2, nrow = 2, widths = c(4, 1.4), heights = c(1.4, 4))

# Customized scatter plots ----
# Basic scatter plot
ggplot(mtcars, aes(x = wt, y = mpg)) + 
    geom_point() +
    geom_smooth(method = lm, color = "black")+
    labs(title = "Miles per gallon \n according to the weight",
         x = "Weight (lb/1000)", y  =  "Miles/(US) gallon") +
    theme_classic()  
# Change color/shape by groups
# Remove confidence bands
p <- ggplot(mtcars, aes(x = wt, y = mpg, color = cyl, shape = cyl)) + 
    geom_point() +
    geom_smooth(method = lm, se = FALSE, fullrange = TRUE) +
    labs(title = "Miles per gallon \n according to the weight",
         x = "Weight (lb/1000)", y  =  "Miles/(US) gallon")
p + theme_classic() 

# Continuous colors
p + scale_color_brewer(palette = "Paired") + theme_classic()
# Discrete colors
p + scale_color_brewer(palette = "Dark2") + theme_minimal()
# Gradient colors
p + scale_color_brewer(palette = "Accent") + theme_minimal()

# 3. ggpubr::ggscatter() ----
# Load data
data("mtcars")
df <- mtcars
df$cyl <- as.factor(df$cyl)
head(df[, c("wt", "mpg", "cyl")], 3)

# Basic plot
# +++++++++++++++++++++++++++
ggscatter(df, x = "wt", y = "mpg",
    color = "black", shape = 21, size = 3, # Points color, shape and size
    add = "reg.line", # Add regressin line
    add.params = list(color = "blue", fill = "lightgray"), # Customize reg. line
    conf.int = TRUE, # Add confidence interval
    cor.coef = TRUE, # Add correlation coefficient. see ?stat_cor
    cor.coeff.args = list(method = "pearson", label.x = 3, label.sep = "\n"))

# loess method: local regression fitting
ggscatter(df, x = "wt", y = "mpg",
    add = "loess", conf.int = TRUE)

# Control point size by continuous variable values ("qsec")
ggscatter( df, x = "wt", y = "mpg",
    color = "#00AFBB", size = "qsec")

# Change colors
# +++++++++++++++++++++++++++
# Use custom color palette
# Add marginal rug
ggscatter(df, x = "wt", y = "mpg",
    color = "cyl", palette = c("#00AFBB", "#E7B800", "#FC4E07"))

# Add group ellipses and mean points
# Add stars
# +++++++++++++++++++
ggscatter(df, x = "wt", y = "mpg",
    color = "cyl", shape = "cyl", palette = c("#00AFBB", "#E7B800", "#FC4E07"),
    ellipse = TRUE, mean.point = TRUE, star.plot = TRUE)

# Textual annotation
# +++++++++++++++++
df$name <- rownames(df)
ggscatter(df, x = "wt", y = "mpg",
    color = "cyl", palette = c("#00AFBB", "#E7B800", "#FC4E07"),
    label = "name", repel = TRUE)
